package org.manager.units;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.manager.generic.web.JsonViewUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * 单位管理控制层
 * 
 * @author zxf_niomp
 * 
 */
@Controller
@RequestMapping("/sysunits")
public class SysUnitsController {

	@Resource(name = "sysUnitsRepository")
	private SysUnitsRepository unit;
	
	private static final String sysUnitAllField[] = new String[]{"id","code","unitCode","unitName","unitParentCode","unitParentId","privateIntegerunitLevel","unitAddress","unitMobile","unitFax","unitRemark","privateIntegerunitOrder","unitControl","privateDateunitDate","masterId","masterName","subCode","privateintpropertiesCount","parentUnitName"};

	/**
	 * 分页查询单位列表数据grid
	 * 
	 * @param code
	 * @param start
	 * @param limit
	 * @return
	 */
	@RequestMapping(params = "method=page")
	public ModelAndView page(HttpServletRequest request,
			HttpServletResponse response,String code, String start, String limit) {
		
		String searchCode = request.getParameter("searchCode");
		String searchName = request.getParameter("searchName");
		int istart = 0;
		int ilimit = 9;
		if(NumberUtils.isNumber(start)){
			istart = NumberUtils.toInt(start);
			if(istart > 1){
				istart = istart/ilimit;
			} 
		}
		
		if(NumberUtils.isNumber(limit) && NumberUtils.toInt(limit)>0){
			ilimit = NumberUtils.toInt(limit);
		}
		SysUnits sysUnit = new SysUnits();
		if(searchCode!=null && !searchCode.equals("")){
			sysUnit.setCode(StringUtils.trimToEmpty(searchCode));
		}
		if(searchName!=null && !searchName.equals("")){
			sysUnit.setUnitName(StringUtils.trimToEmpty(searchName));
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("totalProperty", unit.totalRecord(sysUnit));
		map.put("data", unit.findPageSysUnits(sysUnit, istart, ilimit));
		map.put("start", istart);
		map.put("limit", ilimit);

		return JsonViewUtil.getSuccessViewWithIncludProperty(map, sysUnitAllField);
	}

	/**
	 * 树(tree)查询
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(params = "method=getTreeNode")
	public ModelAndView getTreeNode(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		response.setContentType("text");
		response.setCharacterEncoding("UTF-8");
		SysUnits param = new SysUnits();
		param.setUnitParentCode(request.getParameter("node"));
		List<SysUnits> nrlist = unit.findBySysUnits(param);
		StringBuffer sb = new StringBuffer();
		boolean isLeaf = false;
		String icon = "";
		sb.append("[");
		for (int i = 0; i < nrlist.size(); i++) {
			SysUnits nr = nrlist.get(i);
			if (nr.getPropertiesCount() == 0) {
				isLeaf = true;
			}
			icon = isLeaf ? "file" : "folder";
			sb.append("{\"text\" :\"" + nr.getUnitName() + "\" ,\"id\" :\""
					+ nr.getUnitCode() + "\",\"leaf\":" + isLeaf
					+ " ,\"cls\" :\"" + icon + "\"},");
		}
		sb.append("]");
		return JsonViewUtil.getSuccessViewWithStringDataArray(sb.toString());
	}
	
	/**
	 * 加载单个数据(tree)
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(params = "method=findByCodeTree")
	public ModelAndView findByCodeTree(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		response.setContentType("text");
		response.setCharacterEncoding("UTF-8");
		SysUnits content = unit.findSysUnitsByEntity(request.getParameter("id"));
		StringBuffer sb = new StringBuffer();
		sb.append("{");
		sb.append("success : true,");
		sb.append("data : {id :\"" + content.getId() + "\" ,unitCode : \""
				+ content.getUnitCode() + "\",unitParentCode : \""
				+ content.getUnitParentCode() + "\"," + "unitName : \""
				+ content.getUnitName() + "\",code : \"" + content.getCode()
				+ "\",unitAddress : \""
				+ StringUtils.trimToEmpty(content.getUnitAddress()) + "\","
				+ "unitMobile: \""
				+ StringUtils.trimToEmpty(content.getUnitMobile())
				+ "\",unitFax : \""
				+ StringUtils.trimToEmpty(content.getUnitFax())
				+ "\",unitOrder:" + content.getUnitOrder() + ",unitRemark:\""
				+ StringUtils.trimToEmpty(content.getUnitRemark())
				+ "\",parentUnitName : \""
				+ StringUtils.trimToEmpty(getParentUnitName(content.getUnitParentCode())) + "\",unitParentId: \""+StringUtils.trimToEmpty(content.getUnitParentId())+"\"}");
		sb.append("}");
		return JsonViewUtil.getSuccessViewWithStringDataArray(sb.toString());
	}

	/**
	 * 加载单个数据
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(params = "method=findByCode")
	public ModelAndView findByCode(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		response.setContentType("text");
		response.setCharacterEncoding("UTF-8");
		SysUnits content = unit.get(request.getParameter("id"));
		StringBuffer sb = new StringBuffer();
		sb.append("{");
		sb.append("success : true,");
		sb.append("data : {id :\"" + content.getId() + "\" ,unitCode : \""
				+ content.getUnitCode() + "\",unitParentCode : \""
				+ content.getUnitParentCode() + "\"," + "unitName : \""
				+ content.getUnitName() + "\",code : \"" + content.getCode()
				+ "\",unitAddress : \""
				+ StringUtils.trimToEmpty(content.getUnitAddress()) + "\","
				+ "unitMobile: \""
				+ StringUtils.trimToEmpty(content.getUnitMobile())
				+ "\",unitFax : \""
				+ StringUtils.trimToEmpty(content.getUnitFax())
				+ "\",unitOrder:" + content.getUnitOrder() + ",unitRemark:\""
				+ StringUtils.trimToEmpty(content.getUnitRemark())
				+ "\",parentUnitName : \""
				+ StringUtils.trimToEmpty(getParentUnitName(content.getUnitParentCode())) + "\",unitParentId: \""+StringUtils.trimToEmpty(content.getUnitParentId())+"\"}");
		sb.append("}");
		return JsonViewUtil.getSuccessViewWithStringDataArray(sb.toString());
	}
	
	public String getParentUnitName(String unitParentId){
		if(unitParentId==null || unitParentId.equals("")){
			return "";	
		}else{
			SysUnits sysunit = new SysUnits();
			sysunit.setUnitCode(unitParentId);
			List<SysUnits> syslist=unit.findBySysUnits(sysunit);
			if(syslist!=null && syslist.size()>0){
				SysUnits s =syslist.get(0);
				return s.getUnitName();
			}
			
		}
		return null;
	}

	/**
	 * 添加前绑定数据
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(params = "method=findByCodeSave")
	public ModelAndView findByCodeSave(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		response.setContentType("text");
		response.setCharacterEncoding("UTF-8");
		SysUnits content = unit.get(request.getParameter("id"));
		StringBuffer sb = new StringBuffer();
		sb.append("{");
		sb.append("success : true,");
		sb.append("data : {id :\"\" ,unitCode : \"\",unitParentCode : \""
						+ content.getUnitCode()
						+ "\","
						+ "unitName : null,code : null,unitAddress : \"\","
						+ "unitMobile: \"\",unitFax : \" \",unitOrder: '' ,unitRemark:\"\",parentUnitName : \""
						+ StringUtils.trimToEmpty(getParentUnitName(content.getUnitCode()))
						+ "\",unitParentId: \""+StringUtils.trimToEmpty(content.getId())+"\"}");
		sb.append("}");
		return JsonViewUtil.getSuccessViewWithStringDataArray(sb.toString());
	}
	
	/**
	 * 添加前绑定数据(Tree)
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(params = "method=findByCodeSaveTree")
	public ModelAndView findByCodeSaveTree(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		response.setContentType("text");
		response.setCharacterEncoding("UTF-8");
		SysUnits content = unit.findSysUnitsByEntity(request.getParameter("id"));
		StringBuffer sb = new StringBuffer();
		sb.append("{");
		sb.append("success : true,");
		sb.append("data : {id :\"\" ,unitCode : \"\",unitParentCode : \""
						+ content.getUnitCode()
						+ "\","
						+ "unitName : null,code : null,unitAddress : \"\","
						+ "unitMobile: \"\",unitFax : \" \",unitOrder: '' ,unitRemark:\"\",parentUnitName : \""
						+ StringUtils.trimToEmpty(getParentUnitName(content.getUnitCode()))
						+ "\",unitParentId: \""+StringUtils.trimToEmpty(content.getId())+"\"}");
		sb.append("}");
		return JsonViewUtil.getSuccessViewWithStringDataArray(sb.toString());
	}

	/**
	 * 删除单位信息
	 * @param ids
	 * @return
	 */
	@RequestMapping(params="method=deleteSysUnits")
	public ModelAndView del(String ids){
		String id[] = ids.split(",");
		if(StringUtils.isNotBlank(ids)){
			for(String s : id){
				unit.deleteByKey(s);
			}
			return JsonViewUtil.getSuccessView();
		}
		return JsonViewUtil.getFailureView();
	}
	
	/**
	 * 删除单位节点tree
	 * @param ids
	 * @return
	 */
	@RequestMapping(params="method=deleteByCode")
	public ModelAndView deleteByCode(String unitCode){
		if(StringUtils.isNotBlank(unitCode)){
			SysUnits uObj =unit.findSysUnitsByEntity(unitCode);
			unit.deleteByKey(uObj.getId());
			return JsonViewUtil.getSuccessView();
		}
		return JsonViewUtil.getFailureView();
	}
	
	/**
	 * 插入和修改
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(params = "method=insertOrUpdateCode")
	public ModelAndView insertOrUpdateCode(HttpServletRequest request,
			HttpServletResponse response, SysUnits sysunits) throws Exception {
		response.setContentType("text");
		response.setCharacterEncoding("UTF-8");
		Serializable id = null; 
		if(StringUtils.isBlank(sysunits.getUnitParentId())){  
			sysunits.setUnitParentId(null);
		}
		String result = "";
		if (sysunits.getId() == null || sysunits.getId().equals("")) {
			id = unit.addSysUnits(sysunits);
			if(id!=null){
				result = "{message:'插入成功!',success:true}";
			}
		} else {
				unit.update(sysunits);
				result = "{message:'修改成功!',success:true}";
		}
		return JsonViewUtil.getSuccessViewWithStringDataArray(result);
	}
	
	@RequestMapping(params = "method=valCode")
	public ModelAndView valCode(HttpServletRequest request,
			HttpServletResponse response, SysUnits sysunits) throws Exception {
		response.setContentType("text");
		response.setCharacterEncoding("UTF-8");
		String val = request.getParameter("val");
		System.out.println("参数："+val);
		String	result = "";
		if(val.equals("111")){
			result = "{message:'成功!',success:true}";
		}
		System.out.println("返回值："+result);
		return JsonViewUtil.getSuccessViewWithStringDataArray(result);
	}
	
	@RequestMapping(params="method=selectAll")
	public ModelAndView selectAll(){
		return JsonViewUtil.getSuccessViewWithIncludProperty(unit.findAll(), sysUnitAllField);
	}

}
